<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 15-1-8
 * Time: 下午4:30
 */

class CallnameStudentController extends \BaseController
{
    /**
     * 返回某个点名列表的所有学生.
     *
     * @param $listId
     * @return \Illuminate\Http\JsonResponse
     * 返回的JSON格式：
     * [
     *      {
     *          "id": "id",
     *          "name": "姓名",
     *          "number": "学号",
     *          "absent_times": "缺勤次数"
     *      },
     *      //注意是个数组...
     * }
     */
    public function index($listId)
    {
        return Response::json(
            Callname_List::findOrFail($listId)['student']
        );
    }

    /**
     * 为某个点名列表添加学生，所提交的数据必须具备下列字段：
     * [单一学生]
     *  name: 学生姓名
     *  number: 学生学号
     * [提交为数组]
     *  students: 数组，具备字段：name、number
     *
     * @param $listId
     * @return \Illuminate\Http\JsonResponse
     *
     * 若成功，则返回:
     * [提交为数组]
     * {
     *      quantity: "成功添加的学生的数目"
     * }
     * [提交为单一学生]
     * {
     *  "id": "id"
     * }
     */
    public function store($listId)
    {
        $this->checkListOwner($listId);

        $validator = $this->getStoreValidator(Input::all());

        if( $validator->passes() ){

            if( Input::get('students', null) ){
                $students = Input::get('students');

                DB::transaction(function()use($students, $listId){
                    foreach ($students as $curr) {
                        Callname_Student::create([
                            'name'=>$curr['name'],
                            'number'=>$curr['number'],
                            'callname_list_id'=>$listId
                        ]);
                   }
                });

                return Response::json([
                   'quantity'=>count($students)
                ]);
            }else{
                $add = Callname_Student::create([
                    'name'=>Input::get('name'),
                    'number'=>Input::get('number'),
                    'callname_list_id'=>$listId,
                ]);

                return Response::json([
                    'id'=>$add['id']
                ]);
            }

        }else{
            return Response::json([
               'error'=>$this->changeValidatorMessageToString($validator->getMessageBag())
            ]);
        }
    }

    /**
     * 生成数据校验器.
     *
     * @param $postData
     * @return \Illuminate\Validation\Validator
     */
    protected function getStoreValidator($postData)
    {
        if( isset($postData['students']) ){
            $rules = [
                'students'=>'required|array|check_students'
            ];

            $messages = [
              'check_students'=>'列表必须具备学生的姓名和学号'
            ];

            Validator::extend('check_students', function($attribute, $value, $params){
                foreach($value as $currentStudent){
                    if( !isset($currentStudent['name']) || !isset($currentStudent['number']) ){
                        return false;
                    }
                }

                return true;
            });

            return Validator::make($postData, $rules, $messages);

        }else{
            $rules = [
                'name'=>'required|max:20|min:2',
                'number'=>'required|integer'
            ];

            return Validator::make($postData, $rules);
        }

    }

    /**
     * 按id，查询某个学生信息.
     *
     * @param $listId
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的ＪＳＯＮ格式如下：
     *
     * {
     *          "id": "id",
     *          "name": "姓名",
     *          "number": "学号",
     *          "absent_times": "缺勤次数"
     * }
     */
    public function show($listId, $id)
    {
        $this->checkListOwner($listId);

        $target = $this->getStudentOnList($listId, $id);

        return Response::json($target);
    }

    /**
     * 更改学生信息，　字段如下：
     *  name: 姓名,
     *  number: 学号,
     *  absent_times: １表示増１
     * @param $listId
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function update($listId, $id)
    {
        $this->checkListOwner($listId);

        $target = $this->getStudentOnList($listId, $id);

        $baseInfo = array_only(Input::all(), ['name', 'number']);
        $target->update($baseInfo);

        if( Input::get('absent_times', null) ){
            $target->update([
               'absent_times'=>  $target['absent_times'] + Input::get('absent_times')
            ]);
        }

        return Response::make('', 200);
    }
    /**
     *
     * 删除某个学生
     * @param $listId
     * @param $ids
     * @return \Illuminate\Http\Response
     * @throws Exception
     */
    public function destroy($listId, $ids)
    {
        $this->checkListOwner($listId);

        $idArray = explode('-', $ids);

        Callname_Student::where('callname_list_id', $listId)
            ->whereIn('id', $idArray)->delete();


        return Response::make('', 200);
    }


    /**
     * 检查当前的用户是否是列表的创建者，若不是则没有
     * 访问权限（抛出异常）
     * @param $listId
     */
    protected function checkListOwner($listId)
    {
        Callname_List::where('id', $listId)
            ->where('creater_id', Auth::user()['id'])
            ->firstOrFail();
    }

    /**
     * 指定列表中查找学生.
     *
     * @param $listId
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    protected function getStudentOnList($listId, $id)
    {
        return Callname_Student::where('id', $id)
            ->where('callname_list_id', $listId)
            ->firstOrFail();
    }
}